package com.demo.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author : YU.TAN
 * @date : 2021/11/15 14:23
 */
public class TcpServerDemo1 {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = null;
        InputStream inputStream = null;
        Socket accept = null;
        ByteArrayOutputStream baos = null;

        try {
            socket = new ServerSocket(9000);

            accept = socket.accept();

            inputStream = accept.getInputStream();

            //管道流
            baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = -1;

            while ((len = inputStream.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }

            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (accept != null) {
                accept.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
        }
    }
}
